#include "thread.h"
#include<shadow.h>

int recvn(int sockfd, void *buf, int length){
    int total = 0; //已经收到的总长度,从给定的套接字（sockfd）中接收指定长度（length）的数据，并将数据保存在缓冲区（buf）中。
    char *p = (char *)buf;
    while(total < length){
        ssize_t sret = recv(sockfd,p+total,length-total,0);
        if (sret == 0) {
            // 连接关闭
            fprintf(stderr, "Connection closed by peer.\n");
            return -1;
        } else if (sret < 0) {
            // 错误处理
            perror("recv");
            return -1;
        }
        total += sret;
    }
    return 0;
}
void getSalt(char* salt, char* cryptPasswd) {
    int i, j;
    for(i = 0, j = 0; cryptPasswd[i] && j != 3; i++) {
        if(cryptPasswd[i] == '$') j++; 
    }
    strncpy(salt, cryptPasswd, i-1);
}

int justify_Login_info(userinfo_t* userinfo, int netfd)
{
    struct spwd* sp;
    char salt[512] = {0};
    
    train_t newFile;
    recvn(netfd, &newFile.length, sizeof(newFile.length));
    recvn(netfd, newFile.buf, newFile.length);

    sp = getspnam(userinfo->username);
    if (sp == NULL) {
        perror("getspnam");
        return 0; // 根据用户名查询错误
    }

    getSalt(salt, sp->sp_pwdp);

    // 验证密码
    if (strcmp(sp->sp_pwdp, crypt(userinfo->password, salt)) == 0) {
        return 1; // 返回1表示验证通过
    } else {
        return 0; // 返回0表示验证失败
    }
}


